import 'dart:io';
import 'package:base_flutter/base_flutter.dart' as b;
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ls_work/a_elder/models/code_value_entity.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_yyt/models/dynamic_entity.dart';
import 'package:ls_work/a_yyt/models/upload_entity.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:ls_work/login/page/user_manager.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/event_bus.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/base_dialog.dart';
import 'package:ls_work/widgets/click_item.dart';
import 'package:ls_work/widgets/load_image.dart';
import 'package:ls_work/widgets/locale_photo_browser.dart';

import '../../net/response/nurse_record_detail_response.dart';
import '../../util/ext_utils.dart';
import '../widget/elder_info_title_cell.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:date_format/date_format.dart';
import 'package:ls_work/a_yyt/page/pending_single_Staff_page.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:permission_handler/permission_handler.dart';

class ElderCareSendPage extends StatefulWidget {
  final CodeValue? info;
  final int? customerId;
  final ElderInfo? elderInfo;
  NurseRecordDetailResponse? detail;
  ElderCareSendPage({ this.info, this.customerId, this.elderInfo,this.detail});
  @override
  _ElderCareSendPageState createState() => _ElderCareSendPageState();
}

class _ElderCareSendPageState extends State<ElderCareSendPage> {
  TextEditingController textFieldEditer = TextEditingController();
  String _recordTime = '';
  int _groupValue = -1;
  List<String> _staffNameList = [];
  List<int> _staffIdList = [];
  List<PendingSelectedGroupEntity> orginList = [];
  FocusNode textFocusNode = FocusNode();

  // List<File> imageList = [];
  List<Upload> imagePathList = [];

  @override
  void initState() {
    if(widget.detail!=null){
      var detail = widget.detail!.bean!;
      _recordTime = detail.recordTime??"";
      textFieldEditer.text = detail.content??"";
      _groupValue = (detail.isShift??-1).toInt();
      _staffNameList = (detail.notifier??"").split(",");
      _staffIdList = detail.notifierIds.isNullOrEmpty()?[]: (detail.notifierIds??"").split(",").map((e)=>e.toInt()!).toList();
      imagePathList = (detail.attachList??[]).map((e)=>Upload.fromJson(e.toJson())).toList();
    }else{
      textFieldEditer.text = widget.info?.nameCn??"";
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getAllByCurBranchWithUsers();
    });
    super.initState();
  }

  @override
  void dispose() {
    textFieldEditer.dispose();
    super.dispose();
  }

  _send() async {
    if (TextUtil.isEmpty(_recordTime)) {
      Toast.show("请选择发生时间");
      return;
    }
    if (_groupValue == -1) {
      Toast.show("请选择是否列入交班");
      return;
    }
    var map = {
      'customerElderId': widget.customerId,
      'nurseItem': widget.info?.codeValue,
      'content': textFieldEditer.text,
      'isShift': _groupValue,
      'recordTime': _recordTime,
    };
    if(widget.detail!=null){
      map['id'] = widget.detail!.bean!.id;
      map['nurseItem'] = widget.detail!.bean!.nurseItem;
      map['customerId'] = widget.detail!.bean!.customerElderId;

    }
    if (_staffIdList.length > 0) {
      map["noticeList"] = _staffIdList;
    }
    if (imagePathList.length > 0) {
      List temp = [];
      for (var item in imagePathList) {
        var map = {'id': item.id, 'path': item.path};
        temp.add(map);
      }
      map['attachList'] = temp;
    }
    SVProgressHUD page = SVProgressHUD(context);
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.nurseRecord}',data: map.toJsonMapStr(),options: PostRequest.urlencodedHeader)
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            Toast.show(map["msg"]);
            eventBus.emit(Constant.eventElderCareAdd);
            // Navigator.pop(context,true);
            b.Go().pop(result: true);
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      Toast.show(getErrorMessage(e));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('提交'),
        elevation: 0.5,
        actions: [
          TextButton(
            onPressed: _send,
            child: Text(
              '提交',
              style: TextStyle(fontSize: 16, color: Colours.app_main),
            ),
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            ElderInfoTitleCell(
              elderInfo: widget.elderInfo!,
            ),
            Gaps.vGap16,
            ClickItem(
              title: '*发生时间：',
              titleStyle: TextStyles.textDark16,
              contentStyle: TextStyles.textDark16,
              content: _recordTime,
              onTap: _showDateTimePicker,
            ),
            Container(
              padding: EdgeInsets.all(20),
              color: Colors.white,
              alignment: Alignment.topLeft,
              height: 200,
              child: TextField(
                controller: textFieldEditer,
                maxLines: 10,
                maxLength: 3000,
                autofocus: false,
                focusNode: textFocusNode,
                decoration: InputDecoration(
                  hintText: "请输入内容",
                  hintMaxLines: 20,
                  fillColor: Colours.bg_color,
                  filled: true,
                  border: InputBorder.none,
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(left: 15.0),
              padding: EdgeInsets.fromLTRB(0, 5, 20, 5),
              decoration: BoxDecoration(
                border: Border(
                  bottom: Divider.createBorderSide(
                    context,
                    color: Colours.line,
                    width: 1,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Expanded(
                    child: Text(
                      '*是否列入交班',
                      style: TextStyle(color: Colours.text_dark, fontSize: 16),
                    ),
                  ),
                  Radio(
                    value: 1,
                    groupValue: _groupValue,
                    onChanged: (value) {
                      setState(() {
                        _groupValue = value!;
                      });
                    },
                  ),
                  Text('是'),
                  Radio(
                    value: 0,
                    groupValue: _groupValue,
                    onChanged: (value) {
                      setState(() {
                        _groupValue = value!;
                      });
                    },
                  ),
                  Text('否'),
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.only(left: 15.0),
              padding: EdgeInsets.fromLTRB(0, 5, 20, 5),
              decoration: BoxDecoration(
                border: Border(
                  bottom: Divider.createBorderSide(
                    context,
                    color: Colours.line,
                    width: 1,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Expanded(
                    child: Text(
                      '选择特别通知人',
                      style: TextStyle(color: Colours.text_dark, fontSize: 16),
                    ),
                  ),
                  (_staffNameList.length > 0)
                      ? Text('${_staffNameList.join('，')}')
                      : SizedBox(),
                  Gaps.hGap5,
                  ChoiceChip(
                    selected: true,
                    selectedColor: Colors.blue,
                    backgroundColor: Colours.text_gray,
                    label: Text(
                      '  选择  ',
                      style: TextStyle(color: Colors.white),
                    ),
                    onSelected: (value) {
                      textFocusNode.unfocus();
                      AppNavigator.push(
                        context,
                        PendingSingleStaffPage(
                          orginList: orginList,
                          callBack: (selectedList) {
                            setState(() {
                              if (selectedList.length > 0) {
                                _staffNameList.clear();
                                _staffIdList.clear();
                                for (var item in selectedList) {
                                  _staffNameList.add(item.userName??"");
                                  _staffIdList.add(item.humanId??0);
                                }
                              } else {
                                _staffNameList.clear();
                                _staffIdList.clear();
                              }
                            });
                          },
                        ),
                      );
                    },
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(3.0),
                    ),
                  ),
                ],
              ),
            ),

            Gaps.vGap15,
            Padding(
              padding: EdgeInsets.fromLTRB(10, 0, 10, 5),
              child: Text.rich(TextSpan(children: [
                TextSpan(
                  text: '上传图片',
                  style: TextStyles.textDark16,
                ),
                TextSpan(
                  text: '（提示：长按图片可删除图片，最多选择8张图片）',
                  style: TextStyles.textGray12,
                ),
              ])),
            ),
            // Gaps.line,
            Container(
              width: ScreenUtil.getScreenW(context),
              height: (ScreenUtil.getScreenW(context) / 4) * 2,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              color: Colors.white,
              child: GridView.builder(
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4, //每行三列
                  childAspectRatio: 1.0, //显示区域宽高相等
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                ),
                itemCount: imagePathList.length + 1,
                itemBuilder: (context, index) {
                  if (index == imagePathList.length) {
                    return IconButton(
                      onPressed: _pickImageFromSource,
                      icon: LoadAssetImage(
                        "default/add_photo",
                        fit: BoxFit.fill,
                      ),
                    );
                  } else {
                    return InkWell(
                      onTap: () {
                        var files = imagePathList.map((e)=>'${HttpApi.imageHead}${e.id}').toList();
                        // AppNavigator.push(
                        //   context,
                        //   PhotoBrowser(
                        //     imageLocaleList: imageList,
                        //     currentPageValue: index,
                        //   ),
                        // );
                        b.showBigImage(context, files,position: index);
                      },
                      onLongPress: () {
                        _showCupertinoAlertDialog(context, index);
                      },
                      child: Image.network(
                        "${HttpApi.imageHead}${imagePathList[index].id}",
                        fit: BoxFit.cover,
                        headers: {"Cookie":UserManager.cookieStr},
                      ),
                    );
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showCupertinoAlertDialog(BuildContext cxt, int index) {
    showDialog(
      context: cxt,
      builder: (context) {
        return BaseDialog(
          title: "提示",
          child: Text('是否要删除？'),
          onPressed: () {
            setState(() {
              // imageList.removeAt(index);
              imagePathList.removeAt(index);
            });
            Navigator.pop(context);
          },
        );
      },
    );
  }

  ///获取分组
  void _getAllByCurBranchWithUsers() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.getAllByCurBranchWithUsers)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            PendingSelectedGroupSection model =
                PendingSelectedGroupSection.fromJson(map);
            orginList = model.data??[];
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      Toast.show(getErrorMessage(e));
    });
  }

  ///选择图片方式
  _pickImageFromSource() {
    if (imagePathList.length == 8) {
      Toast.show('最多上传8张');
      return;
    }
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("相机"),
                onTap: () async {
                  Navigator.pop(context);
                  Permission.camera.checkRequestPermission(
                    context,
                    onSuccess: () async {
                      var imageFile =
                      await ImagePicker().pickImage(source: ImageSource.camera);
                      if(imageFile!=null){
                        setState(() {
                          // imageList.add(File(imageFile?.path??""));
                          _upLoadImage(File(imageFile?.path??""));
                        });
                      }
                    },
                    msg: "使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限",
                  );

                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("相册"),
                onTap: () async {
                  Navigator.pop(context);
                  var isAndroid13 = await isAndroid13OrAbove();
                  if(isAndroid13){
                    Permission.photos.checkRequestPermission(
                      context,
                      onSuccess: () async {
                        var imageFile =
                        await ImagePicker().pickImage(source: ImageSource.gallery);
                        if(imageFile!=null){
                          setState(() {
                            // imageList.add(File(imageFile?.path??""));
                            _upLoadImage(File(imageFile?.path??""));
                          });
                        }
                      },
                      msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限",
                    );
                  }else{
                    Permission.storage.checkRequestPermission(
                      context,
                      onSuccess: () async {
                        var imageFile =
                        await ImagePicker().pickImage(source: ImageSource.gallery);
                        if(imageFile!=null){
                          setState(() {
                            // imageList.add(File(imageFile?.path??""));
                            _upLoadImage(File(imageFile?.path??""));
                          });
                        }
                      },
                      msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限",
                    );
                  }
                },
              ),
            ],
          );
        });
  }

  ///上传
  _upLoadImage(File image) async {
    String path = image.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var fileType = name.split(".").last;
    FormData formData = new FormData.fromMap({
      'fileType': fileType,
      'fileToUpload': await MultipartFile.fromFile(path, filename: name),
    });
    HttpUtil.instance.getDio().post(HttpApi.upload, data: formData).then((r) {
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            Upload model = Upload.fromJson(map['data']);
            setState(() {
              imagePathList.add(model);
            });
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      Toast.show(getErrorMessage(e));
    });
  }

  ///调起时间选择器
  void _showDateTimePicker() {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("2010-01-01 00:00:00"),
      maxDateTime: DateTime.now(),
      initialDateTime: DateTime.parse(formatDate(DateTime.now(),
          [yyyy, "-", mm, "-", "dd", " ", HH, ":", nn, ":", ss])),
      dateFormat: "yy年M月d日    EEE,H时:m分",
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.datetime,
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          _recordTime =
              DateUtil.formatDate(dateTime, format: 'yyyy-MM-dd HH:mm:ss');
        });
      },
    );
  }
}
